<template>
  <div>
    <el-form inline :model="sysUserQuery" ref="sysQuerFormRef">
      <el-form-item>
        <el-input placeholder="请输入关键字" v-model="sysUserQuery.keywords"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" @click="getUserList">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" @click="resetQueryForm(sysQuerFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
    >
    <el-button @click="openAddDialog" :icon="Plus" size="small" type="primary"
    >新增
    </el-button
    >
    <el-table
        :data="sysUserPage.list"
        style="width: 100%"
        v-loading="dataLoading"
        element-loading-text="拼命加载中..."
    >
      <el-table-column label="头像">
        <template #default="scope">
          <el-avatar shape="square" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="用户Id"/>
      <el-table-column prop="userName" label="用户名"/>
      <el-table-column prop="nickName" label="昵称"/>
      <el-table-column prop="sex" label="性别"/>
      <el-table-column prop="phone" label="手机号"/>
      <el-table-column prop="status" label="状态"/>
      <el-table-column prop="remark" label="备注"/>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button @click="openUpdateDialog(scope.row)" type="warning" size="small" :icon="Edit">修改</el-button>
          <el-divider direction="vertical"/>
          <el-button @click="del(scope.row.userId)" type="danger" :icon="Delete" size="small">删除</el-button>
          <el-divider direction="vertical"/>
          <el-dropdown>
            <el-button type="primary" size="small" class="el-dropdown-link">
              更多
              <el-icon class="el-icon--right">
                <arrow-down/>
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="openAuthRole(scope.row.userId)">分配角色</el-dropdown-item>
                <el-dropdown-item>Action 2</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
          size="small"
          background
          layout="prev, pager, next"
          :total="sysUserPage.total"
          v-model:page-size="sysUserQuery.pageSize"
          v-model:current-page="sysUserQuery.pageNum"
      />
    </div>
    <el-dialog
        v-model="dialogFormVisible"
        :title="dialogType === 0 ? '新增' : '修改'"
        width="500"
    >
      <el-form :model="sysUser" label-width="80px" :rules="rules" ref="ruleFormRef">
        <el-form-item label="头像">
          <AvatarUpload @filePath="getFilePath" :imageUrl="sysUser.avatar"></AvatarUpload>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="sysUser.userName"/>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="sysUser.nickName"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="sysUser.status">
            <el-radio :value="0">启用</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="sysUser.sex">
            <el-radio :value="0">男</el-radio>
            <el-radio :value="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="sumbitUser(ruleFormRef)"> 确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
        v-model="authRoleDialogVisible"
        title="分配角色"
        width="500"
    >
      <div>
        <el-table @selection-change="handleSelectionChange" :data="rolePage.list" style="width: 100%" row-key="roleId"
                  ref="authRoleRef">
          <el-table-column type="selection" width="55"/>
          <el-table-column property="roleId" label="编号" width="120">
          </el-table-column>
          <el-table-column property="roleName" label="权限名" width="120"/>
          <el-table-column property="roleKey" label="角色标识"/>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="authRoleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAuth">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {reactive, ref, onMounted, watch} from "vue";
import {ElMessage, ElMessageBox,} from "element-plus";
import type {FormInstance, FormRules} from 'element-plus'
import {Plus, Search, Delete, Edit, ArrowDown} from "@element-plus/icons-vue";
import type {SysUser, SysUserQuery} from "@/api/system/user/type";
import {
  reqGetSysUserPage,
  reqAddSysUser,
  reqModifySysUser,
  reqSysUserAuth,
  reqDeleteSysUserById
} from "@/api/system/user";
import {reqGetSysRoleIdByUserId, reqGetSysRolePage} from "@/api/system/role";
import AvatarUpload from "@/components/common/AvatarUpload.vue";
import {SysRole} from "@/api/system/role/type";

let sysUserPage = reactive({
  total: 0,
  list: [] as SysUser[],
  pageNum: 0
})
let dialogFormVisible = ref<boolean>(false);
let dialogType = ref(0); //0新增，1修改
let dataLoading = ref(true);
let authRoleDialogVisible = ref(false)
let ruleFormRef = ref<FormInstance>()
let sysQuerFormRef = ref()
let sysUserQuery = reactive<SysUserQuery>({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
  status: -1,
  phone: "",
});

let sysUser = reactive<SysUser>({
  userId: "",
  userName: "",
  nickName: "",
  sex: 0,
  status: 0,
  remark: "",
  avatar: "",
  phone: "",
});
let sysRoleQuery = reactive({
  keywords: "",
  pageNum: 1,
  pageSize: 20,
});
let authRoleRef = ref()
let authRoleForm = reactive({
  roleIds: [] as string[],
  userId: ""
})
let rolePage = reactive({
  total: 0,
  list: [] as SysRole[]
})
let userAuthRole = reactive({
  userId: "",
  roleIds: [] as string[],
});
let rules = reactive<FormRules<SysUser>>({
  userName: [{required: true, message: "请输入用户名", trigger: "blur",},],
  password: [{required: true, message: "请输入密码", trigger: "blur",},],
  nickName: [{required: true, message: "请输入昵称", trigger: "blur",},],
  phone: [{required: true, message: "请输入手机号", trigger: "blur",},]
})

function getUserList() {
  reqGetSysUserPage(sysUserQuery).then((res) => {
    sysUserPage.list = res.data.list;
    sysUserPage.total = res.data.total;
    dataLoading.value = false;
  });
}

const resetQueryForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

function getFilePath(path: string) {
  sysUser.avatar = path;
}

function openAddDialog() {
  dialogType.value = 0;
  dialogFormVisible.value = true;
}

//将选中的行的roleId放入roleIds中
let handleSelectionChange = (val: SysRole[]) => {
  userAuthRole.roleIds = val.map(item => item.roleId) as string[]
}
let submitAuth = () => {
  if (userAuthRole.roleIds.length > 0) {
    reqSysUserAuth(userAuthRole).then(res => {
      ElMessage({
        message: "操作成功！",
        type: "success",
      });
    })
  }
  authRoleDialogVisible.value = false
}

let openAuthRole = async (userId: string) => {
  userAuthRole.userId = userId
  let res = await reqGetSysRolePage(sysRoleQuery)
  rolePage.list = res.data.list
  authRoleDialogVisible.value = true
  let res2 = await reqGetSysRoleIdByUserId(userId)
  authRoleForm.roleIds = res2.data
  rolePage.list.forEach(item => {
    if (authRoleForm.roleIds.includes(item.roleId)) {
      authRoleRef.value.toggleRowSelection(item, true);
    }
  })
}

function openUpdateDialog(user: SysUser) {
  Object.assign(sysUser, user);
  dialogType.value = 1;
  dialogFormVisible.value = true;
}

async function sumbitUser(formEl: FormInstance | undefined) {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (dialogType.value === 0) {
        reqAddSysUser(sysUser);
      } else reqModifySysUser(sysUser);
      dialogFormVisible.value = false;
      ElMessage({
        message: "操作成功！",
        type: "success",
      });
    } else {
      console.log('error submit!', fields)
    }
  })
}

function del(userId: string) {
  ElMessageBox.confirm("删除之后无法恢复，请确认是否删除？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(() => {
        reqDeleteSysUserById(userId).then(() => {
          ElMessage({
            message: "删除成功！",
            type: "success",
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除！",
        })
      })
}

onMounted(() => {
  getUserList();
});

watch([() => sysUserQuery.pageNum, () => sysUserQuery.pageSize], () => {
  getUserList()
})
</script>
<style lang="scss"></style>
